package com.ethan.crm.util;

import com.ethan.crm.domain.Employee;
import com.ethan.crm.domain.Log;
import com.ethan.crm.service.ILogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


public class LogUtil {

    @Autowired
    private ILogService logService;

    /**
     * 注意 因为该方法是在service层的某个方法执行后进行的，
     * 因为我们设置了service层的事务。加上AOP的特性，所以该方法是可能包含到service层的事务中的。
     *
     * @param joinPoint
     */
    public void writeLog(JoinPoint joinPoint){
        //因为设置了切面为service层，而最下面 logService.insert(log)也属于service层就导致一直在service层进行循环切面操作
        // 防止AOP拦截logService本身，造成死循环
        if (joinPoint.getTarget() instanceof ILogService){
            return;
        }

        Log log = new Log();
        log.setOptime(new Date());
        HttpServletRequest request = UserContext.get();
        Employee currentUser = (Employee) request.getSession().getAttribute(UserContext.USER_IN_SESSION);
        String ip = request.getRemoteAddr();
        log.setOpuser(currentUser);
        log.setOpip(ip);
        String functionName = joinPoint.getTarget().getClass().getName()+":"+joinPoint.getSignature().getName();
        log.setFunction(functionName);

        try {
            ObjectMapper mapper = new ObjectMapper();
            String params = mapper.writeValueAsString(joinPoint.getArgs());
            log.setParams(params);
            System.out.println(params);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //将日志信息插入到数据库中
        logService.insert(log);

    }
}
